package com.orange.off.cloud.cloudoff.views;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;


@SuppressLint("DrawAllocation")
public class CircleImageView extends ImageView {

	private final Paint paint = new Paint();

	public CircleImageView(Context context) {
		super(context);
	}

	public CircleImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		Drawable drawable = getDrawable();
		if (drawable != null) {
			Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
			if (bitmap == null) {
				return;
			}
			Bitmap b = toRoundCorner(bitmap);
			final Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight());
			paint.reset();
			canvas.drawBitmap(b, rect, rect, paint);
		} else {
			super.onDraw(canvas);
		}
	}

	private Bitmap toRoundCorner(Bitmap bitmap) {
		int width = getMeasuredWidth();
		int height = getMeasuredHeight();
		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		int side = (bitmap.getWidth() > bitmap.getHeight()) ? bitmap
				.getHeight() : bitmap.getWidth();
		final Rect src = new Rect(0, 0, side, side);
		final Rect dest = new Rect(0, 0, width, height);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		int x = width;
		int rim = 0;
		canvas.drawCircle(x / 2, x / 2, (x / 2) - (rim * 0), paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dest, paint);

		final int color2 = 0xff424242;
		paint.setColor(color2);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
		canvas.drawCircle(x / 2, x / 2, x / 2, paint);

		return output;
	}

}
